package ru.spbsu.electromenu.servlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Date: 3/23/11
 * Time: 8:01 AM
 *
 * @author Artem Titov
 */
public class SpringHttpServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(SpringHttpServlet.class);

    protected boolean isValid = true;

    protected <T> T getBean(final String name) {
        WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        if (springContext == null) {
            logger.warn("Failed to get web application context. Context is NULL");
            isValid = false;
            throw new IllegalStateException("WebApplicationContext is null");
        }
        return (T) springContext.getBean(name);
    }

    protected int getParameter(final HttpServletRequest request, final String name, final int defaultValue) {
        logger.debug("Getting parameter name: {}. Value is {}", name, request.getParameter(name));
        try {
            return Integer.parseInt(request.getParameter(name));
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    protected Boolean getParameter(final HttpServletRequest request, final String name, final Boolean defaultValue) {
        logger.debug("Getting parameter name: {}. Value is {}", name, request.getParameter(name));
        if (request.getParameter(name) != null) {
            return Boolean.parseBoolean(request.getParameter(name));
        } else {
            return defaultValue;
        }
    }

    protected HttpServletRequest resolve(HttpServletRequest request) throws IOException {
        final MultipartResolver multipartResolver = new CommonsMultipartResolver();
        if (multipartResolver.isMultipart(request)) {
            request = multipartResolver.resolveMultipart(request);
        }
        return request;
    }
}
